package com.rio.core;

import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

import com.rio.core.U;

/**
 * @author rio.lv
 *
 */
public class M {
	
	private static ConcurrentHashMap<String, Object> mCacheMap;
	
	private static ConcurrentHashMap<String, Object> getMap(){
		if(U.isNull(mCacheMap)){
			mCacheMap = new ConcurrentHashMap<String, Object>();
		}
		return mCacheMap;
	}
	
	@SuppressWarnings("unchecked")
	public static <T extends Object> T get(String key){
		if(getMap().containsKey(key)){			
			return (T) getMap().get(key);			
		};		
		return null;		
	}  

	
	public static boolean set(String key,Object value){
		return U.notNull(getMap().put(key, value));
	}
	
	public static void clear(){
		if(U.notNull(mCacheMap)){
			mCacheMap.clear();
		}
		mCacheMap = null;
	}
	
	
	@SuppressWarnings("unchecked")
	public static <T extends Object> T get(String key,BaseMemory callback){
		if(getMap().containsKey(key)){			
			return (T) getMap().get(key);			
		}else{
			T result = callback.create(key);
			if(set(key, result)){
				return result;
			}
		};		
		return null;		
	}
	
}
